package com.tepth.appmanageservice.protocol.packets;

import com.tepth.appmanageservice.protocol.Index;
import com.tepth.appmanageservice.protocol.interfaces.IReceive;
import com.tepth.appmanageservice.protocol.interfaces.ISend;

public class Check implements IReceive, ISend {
	private byte[] header;
	private byte[] body;
	private byte value;
	private byte crc;

	public Check() {

	}

	public Check(byte[] header, byte[] body) {
		this.header = header;
		this.body = body;
	}

	@Override
	public short getId() {
		return 0;
	}

	@Override
	public byte[] getResult() {
		return new byte[] { value };
	}

	@Override
	public short getLength() {
		return 1;
	}

	@Override
	public void setLength(int length) {

	}

	@Override
	public void Receive(byte[] data, Index index) {
		this.value = data[index.get()];
	}

	@Override
	public void load() {
		this.load(this.header, this.body);
	}

	public void load(byte[] header, byte[] body) {
		this.value = 0;
		for (int i = 0; i < header.length; i++) {
			this.value ^= header[i];
		}

		for (int i = 0; i < body.length; i++) {
			this.value ^= body[i];
		}
	}

	public void check(byte[] data) {
		for (int i = 1; i < data.length - 2; i++) {
			this.crc ^= data[i];
		}
	}

	public static void againCheck(byte[] data) {
		byte crc = 0;
		for (int i = 1; i < data.length - 2; i++) {
			crc ^= data[i];
		}
		data[data.length - 2] = crc;
	}

	public Boolean isCheck() {
		return this.crc == this.value;
	}
}